import React from 'react';
import { InputNumber, Space } from 'antd';
import { gt, toNumber } from 'lodash';
import { MinusOutlined } from '@ant-design/icons';
import { input } from './styles.less';

enum INPUT_TYPE {
  MIN,
  MAX,
}

const FormDigitRange: React.FC<any> = ({
  value = [],
  onChange,
  separatorGap = 15,
  min = 0,
  max = 100,
  suffix,
  ...inputNumberProps
}) => {
  // 输入值失去焦点回调
  const handleChangeValue = (e: any, type: INPUT_TYPE) => {
    let result: any = e.target.value !== '' ? toNumber(e.target.value) : undefined;

    const [_min, _max] = value;

    if (result > max) result = max;
    if (result < min) result = min;

    switch (type) {
      case INPUT_TYPE.MIN:
        onChange?.(gt(result, _max) ? [_max, result] : [result, _max]);
        break;
      case INPUT_TYPE.MAX:
        onChange?.(gt(_min, result) ? [result, _min] : [_min, result]);
        break;
    }
  };
  // 渲染输入框
  const renderInputNumber = (type: INPUT_TYPE) => (
    <InputNumber
      {...inputNumberProps}
      min={min}
      max={max}
      value={toNumber(value[type])}
      bordered={false}
      onBlur={e => handleChangeValue(e, type)}
      style={{ width: 72 }}
    />
  );

  return (
    <Space className={input}>
      {renderInputNumber(INPUT_TYPE.MIN)}
      <MinusOutlined />
      {renderInputNumber(INPUT_TYPE.MAX)}
    </Space>
  );
};
export default FormDigitRange;
